<template>
  <div>
    <div class="limiter">
      <div class="container-table103">
        <div class="wrap-table101">
          <!-- 进度条 -->
          <div class="progress_box" style="width:90%;">
            <el-progress class="progress_line" style="width:90%;" v-show="progressShow" :text-inside="true"
              :stroke-width="22" :color="customColor" :percentage="c_percentage" status="warning"></el-progress>
          </div>
          <!-- 进度条 -->
          <!-- <el-upload v-show="!progressShow" class="upload-demo" ref="upload" :auto-upload="autoUpload"
			  :show-file-list="show_file_list" :headers="headers" drag :action="UploadUrl()" :limit="1"
			  :on-exceed="handleExceed" :on-change="onChange" :on-success="handleAvatarSuccess"
			  :on-progress="handleAvatarProgress" :on-error="handleAvatarError">
			  <el-image :src="src"></el-image>
			  <el-button>立即上传</el-button>
			  <div v-show="isvip == 0" class="el-upload__text">
				点击按钮选择应用的安装包，或直接拖拽文件到此区域（支持.IPA或.APK文件，单个文件最大支持{{uploadInfo.singlesize}}M）
			  </div>
			  <div v-show="isvip == 1" class="el-upload__text">
				点击按钮选择应用的安装包，或直接拖拽文件到此区域（支持.IPA文件，单个文件最大支持{{uploadInfo.singlesize}}M）
			  </div>
			</el-upload> -->
          <div>
            <uploader :options="options" :file-status-text="statusText" class="uploader-example" ref="uploader"
              @file-success="fileSuccess" style="width: 100%;">
              <uploader-unsupport></uploader-unsupport>
              <uploader-drop>
                <p>欢迎来到上传录音界面</p>
                <uploader-btn>选择录音</uploader-btn>
              </uploader-drop>
              <uploader-list></uploader-list>
            </uploader>
          </div>

        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import JsZip, {
    files
  } from "jszip";

  export default {
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
      //这里存放数据
      return {
        uploadInfo: {},
        src: "../../../static/上传应用按钮.png",
        headers: {},
        c_percentage: 0, //初始进度0
        progressShow: false, //最开始隐藏进度条

        new_zip: [],
        autoUpload: false,
        show_file_list: false,
        reader_c: "", //当前解压zip实体
        appName: "", //APP名称
        version: "", //版本
        Identifier: "", //包名
        zxlogo: "", //APP图标地址
        sext: "", //后缀地址
        upName: "", //上传地址文件名称
        DownLink: "", //下载地址
        AppSize: 0, //APP包大小
        sjid: 0, //升级ID，0为新上传
        // isvip: 0, //是否为超级签名
        customColor: '#ff7226', //进度条颜色


        recording: {},
        options: {
          // https://github.com/simple-uploader/Uploader/tree/develop/samples/Node.js
          target: "http://upload.ilucode.com/index/uploadfile/uploadbd",
          testChunks: false, //不校验
          chunkSize: '10240000'
        },
        statusText: {
          success: "上传成功",
          error: "上传失败",
          uploading: "上传中",
          paused: "暂停中",
          waiting: "等待中"
        }

      };
    },
    props: ['isvip'],
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
      //上传成功的事件
      fileSuccess(rootFile, file, message) {
        console.log(message);
        //将面试邀请code和文件路径去保存到数据库中
        var href = location.href;
        var split = href.split("?");
        var invCode = split[1];
        this.recording.invCode = invCode;
        this.recording.recordingUrl = message;
        // this.$ajax
        //   .post(
        //     "http://localhost:8080/interview/recording/saveFileData",
        //     JSON.stringify(this.recording),
        //     {
        //       headers: {
        //         "Content-Type": "application/json;charset=UTF-8"
        //       }
        //     }
        //   )
        //   .then(response => {
        //     if ("ok" == response.data) {
        //       console.log("上传成功");
        //     } else {
        //       alert("上传失败");
        //     }
        //   })
        //   .catch(function(error) {
        //     alert("上传失败");
        //     console.log(error);
        //   });

        // var params = new URLSearchParams();
        // // var Authorization = sessionStorage["token"];
        // // this.headers = {
        // //   Authorization: Authorization
        // // };
        // this.$post(this.API.Application_uploadsInfo, params).then((res) => {
        //   if (res) {

        //     // console.log(res);
        //     this.uploadInfo = res.data.result;
        //     console.log(this.uploadInfo);
        //   }
        // })

        // this.uploadsInfo();
        // this.UploadUrl();
      },


      uploadsInfo() {
        var params = new URLSearchParams();
        this.$post(this.API.Application_uploadsInfo, params).then((res) => {
          if (res) {
            // console.log(res);
            this.uploadInfo = res.data.result;
            console.log(this.uploadInfo);
          }
        })
      },

      UploadUrl: function () {
        return this.uploadInfo.fileUploadUrl;
        console.log(this.uploadInfo.fileUploadUrl, "地址");
      },
      handleRemove(file, fileList) {
        // console.log(file, fileList);
      },
      handlePreview(file) {
        // console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
			  files.length + fileList.length
			} 个文件`
        );
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      //文件选取时，判断逻辑
      onChange(file, fileList) {
        // if(this.uploadInfo['rzstatus'] != 1){
        //   this.$message.error("请选实名认证!");
        //   this.$refs.upload.clearFiles();

        //   setTimeout(() => {
        //     this.$router.push({
        //       path: '/realName',
        //       name: 'realName',
        //     }); 
        //   }, 3000);
        //   return;
        // }

        file = file.raw;

        // console.log(file);
        let c_fileName = file.name;
        this.upName = file.name;
        let fileArr = c_fileName.split(".");
        this.sext = fileArr[fileArr.length - 1];
        const isLt2M = file.size / 1024 / 1024 < 100;

        if (this.isvip == 1) {
          if (this.sext != "ipa") {
            this.$message.error("上传文件只能是 ipa 格式!");
            this.$refs.upload.clearFiles();
            return;
          }
        } else {
          if (this.sext != "ipa" && this.sext != "apk") {
            this.$message.error("上传文件只能是 ipa/apk 格式!");
            this.$refs.upload.clearFiles();
            return;
          }
        }

        if (!isLt2M) {
          this.$message.error("上传文件大小不能超过 " + this.uploadInfo.singlesize + "MB!");
          this.$refs.upload.clearFiles();
          return;
        }

        //显示进度条
        this.progressShow = true;

        let that = this;
        that.new_zip = new JsZip();
        that.new_zip.loadAsync(file).then(function (reader) {
          // you now have every files contained in the loaded zip
          that.reader_c = reader;
          var infoplist = null,
            resoucesArsc = null,
            androidManifest = null;
          for (let key in reader.files) {
            if (key.match(/Payload\/([^\\\?\/\*\|<>:"]+\.app\/)Info\.plist/)) {
              infoplist = key;
              continue;
            }
            if (key.match(/AndroidManifest.xml/)) {
              androidManifest = key;
              continue;
            }

            if (key.match(/resources.arsc/)) {
              resoucesArsc = key;
              continue;
            }
          }
          let param = new FormData(); //创建form对象
          if (infoplist != null) {
            that.new_zip
              .file(infoplist)
              .async("blob")
              .then(function (data) {
                param.append("upFile", data);
                param.append("type", "ipad"); //通过append向form对象添加数据
                //发起请求
                that.$post(that.API.Appparser_getAppInfo, param).then((res) => {
                  if (res) {
                    // console.log(res);
                    that.appName = res.data.appName;
                    that.version = res.data.version;
                    that.Identifier = res.data.Identifier;
                    var icon = res.data.icon;
                    that.pre_GetIcon(icon, icon);
                  }
                });
              });
          }

          if (resoucesArsc != null && androidManifest != null) {
            that.new_zip
              .file(androidManifest)
              .async("blob")
              .then(function (data) {
                param.append("upFile", data);
                param.append("type", "android"); //通过append向form对象添加数据
                that.new_zip
                  .file(resoucesArsc)
                  .async("blob")
                  .then(function (data) {
                    param.append("upFIle1", data);
                    //发起请求
                    that
                      .$post(that.API.Appparser_getAppInfo, param)
                      .then((res) => {
                        if (res) {
                          // console.log(res);
                          that.appName = res.data.appName;
                          that.version = res.data.version;
                          // sPackageName = res.data.Identifier;
                          var icon = res.data.icon;
                          that.pre_GetIcon("apk", icon);
                        }
                      });
                  });
              });
          }
        });
      },
      pre_GetIcon(icon, icon2) {
        var LogoName = "/" + icon;
        if (icon.indexOf(".") == -1) {
          LogoName = "/" + icon + "([\\d]+x[\\d]+)?(@[\\d]x)?.png";
        }
        var sys = "ios";
        var logo = "";
        if (icon == "apk") {
          //如果是apk展示这么处理
          LogoName = icon2;

          logo = this.getIconFile(LogoName);
          if (logo == null) {
            LogoName = /\/([\w\W]*)icon([\w\W]*).jpg/gi;
            logo = this.getIconFile(LogoName);
          }
          if (logo == null) {
            LogoName = /\/([\w\W]*)launcher([\w\W]*).png/gi;
            logo = this.getIconFile(LogoName);
          }
          if (logo == null) {
            LogoName = /\/([\w\W]*)launcher([\w\W]*).jpg/gi;
            logo = this.getIconFile(LogoName);
          }
          sys = "apk";
        } else {
          logo = this.getIconFile(LogoName);
        }

        if (logo == null) {
          bError = true;
          alert("上传的文件图标解析失败!");
          this.$refs.upload.clearFiles();
          return false;
        }

        // console.log(logo);
        let that = this;
        that.new_zip
          .file(logo)
          .async("blob")
          .then(function (data) {
            // console.log(data);
            //修改处理获取ios数据处理xml
            //从包中获取icon图片，且上传到服务器上
            //发起请求
            let param = new FormData(); //创建form对象
            param.append("upFile", data);
            param.append("sys", sys);
            that.$post(that.API.Appparser_getIcon, param).then((res) => {
              if (res) {
                // console.log(res);
                that.zxlogo = res.path;
                if (!that.zxlogo || that.zxlogo.length == 0) {
                  // bError = true;
                  alert("上传的文件图标地址失败!");
                  that.$refs.upload.clearFiles();
                  return false;
                }

                that.$refs.upload.submit();
              }
            });
          });

      },
      getIconFile(fileName) {
        var iconFile = null;
        for (let key in this.reader_c.files) {
          if (key.match(new RegExp(fileName, "i"))) {
            iconFile = key;
            break;
          }

        };
      },
      getIconFile(fileName) {
        var iconFile = null;
        for (let key in this.reader_c.files) {
          if (key.match(new RegExp(fileName, "i"))) {
            iconFile = key;
            break;
          }
        }
        return iconFile;
      },
      submitData() {
        var params = new URLSearchParams();
        params.append('DownLink', this.DownLink);
        params.append('hext', this.sext);
        params.append('zxlogo', this.zxlogo);
        params.append('happName', this.appName);
        params.append('iAppSize', this.AppSize);
        params.append('hpackageName', this.Identifier);
        params.append('hversion', this.version);
        params.append('isvip', this.isvip);
        params.append('sjid', this.sjid);
        params.append('apkName', this.upName);
        // console.log(params);
        this.$post(this.API.Appupload_uploadData, params).then((res) => {
          if (res) {
            // console.log(res);
            sessionStorage.setItem("setMenuIndex_application", 1);
            sessionStorage.setItem("setMenuIndex_supuer", 1);
            location.reload();
          }
        })
      },
      handleAvatarSuccess(res, file) {
        this.DownLink = res.path;
        this.AppSize = file.size;
        this.submitData();
        // this.imageUrl = URL.createObjectURL(file.raw);
      },
      handleAvatarProgress(res, file) {
        this.c_percentage = parseInt(res.percent);
        // c_percentage
        // this.imageUrl = URL.createObjectURL(file.raw);
      },
      handleAvatarError(res, file) {
        // console.log(res);
        // this.imageUrl = URL.createObjectURL(file.raw);
      },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
      var Authorization = sessionStorage["token"];
      this.headers = {
        Authorization: Authorization
      };

      var appID = this.$route.query.appID; //appID
      if (appID > 0) {
        this.sjid = appID;
      }

      this.uploadsInfo();
      // console.log('appID:'+this.sjid);
      // console.log('isvip:'+this.isvip);
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
      // 获取uploader对象
      this.$nextTick(() => {
        window.uploader = this.$refs.uploader.uploader;
      });
    },
  };

</script>
<style scoped>
  .uploader-example {
    width: 100%;
    padding: 15px;
    margin: 50px auto 0;
    font-size: 12px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
  }

  .uploader-example .uploader-btn {
    margin-right: 4px;
  }

  .uploader-example .uploader-list {
    max-height: 440px;
    overflow: auto;
    overflow-x: hidden;
    overflow-y: auto;
  }

  .progress_box {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  div>>>.el-button--default {
    border: none;
  }

  .content {
    margin: 30px 0px 30px 0px;
    background: #FFFFFF;
    box-shadow: 0px 4px 10px 2px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
  }

  .limiter {
    width: 100%;
    margin: 0 auto;
  }

  .container-table103 {
    width: 100%;
    min-height: 100vh;
    display: -webkit-box;
    display: -webkit-flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
  }

  .container-table102 {
    width: 100%;
    min-height: 100vh;
    border-radius: 4px 0px 0px 4px;
  }

  .wrap-table101 {
    width: 1170px;
    display: flex;
    justify-content: center;
    align-items: center;
  }


  div>>>.el-upload__input {
    display: none;
  }


  div>>>.el-upload-dragger {
    border: none;
  }

  .el-button {
    width: 180px;
    /* height: 50px; */
    background-color: #ff7226;
    font-size: 16px;
    color: #fff;
    border-radius: 8px;
  }

  div>>>.el-button span {
    margin-left: 40px;
  }

  .el-image {
    position: absolute;
    margin-top: 12px;
    margin-left: 45px;
  }

  .el-upload__text {
    color: #adadad;
    font-size: 12px;
    /* width: 204px; */
    /* margin-left: 80px; */
    margin-top: 10px;
  }

  div>>>.el-upload-dragger {
    width: 180px;
    /* height: 50px; */
  }

  div>>>.upload-demo {
    width: 180px;
    /* height: 50px; */
    position: absolute;
    top: 40%
  }

  /* 媒体查询 */
  @media (max-width: 992px) {
    .container-table103 {
      min-height: 70vh;
    }
  }

  @media (max-width: 576px) {}

</style>
